<template>
    <div class="customer-card">
        <CardTitle title="客户动态" @change="onChangeCardTitle" />
        <el-tabs v-model="activeName" class="demo_tabs" @tab-change="handleClick">
            <el-tab-pane name="first">
                <template #label>
                    行为（有<span class="led"> {{ state?.dataList?.length || 0 }} </span>条动态）
                </template>
                <el-form :inline="true" :model="state.formData" class="demo-form-inline">
                    <el-row style="width: 100%" :gutter="20">
                        <el-col :span="7">
                            <el-form-item label="事件名称">
                                <el-cascader
                                    v-model="state.formData.cascaderValue"
                                    :options="state.cascaderOptions"
                                    :props="cascaderProps"
                                    :show-all-levels="false"
                                    placeholder="请选择"
                                    clearable>
                                </el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="员工">
                                <el-select
                                    v-model="state.formData.userValue"
                                    placeholder="全部"
                                    multiple
                                    popper-class="zw-hide_select_option"
                                    @click.stop="openDepart"
                                    @change="changeDepart">
                                    <el-option
                                        v-for="(item, index) in state.userOption"
                                        :key="index"
                                        :label="item.name"
                                        :value="item.id">
                                        {{ item.name }}
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item>
                                <el-button type="primary" @click="onSubmit(false)">查询</el-button>
                                <el-button @click="onSubmit(true)">清空</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <template v-if="state.dataList.length > 0">
                    <List
                        :is-loading="isLoading"
                        :sorter="state.sorter"
                        :data-list="state.dataList"
                        @change="onChangeList" />
                </template>
                <el-empty v-else image="/static/noData.png" description="暂无数据"></el-empty>
            </el-tab-pane>
            <el-tab-pane label="跟进" name="second">
                <FollowTable
                    v-if="activeName == 'second'"
                    ref="FollowTableRef"
                    :step-list="stepList"
                    :filter-time="state.filterTime"
                    follow-type="dynamic" />
            </el-tab-pane>
            <el-tab-pane v-if="!isReal" label="商机" name="third">
                <Business v-if="activeName == 'third'" ref="BusinessRef" :is-company="isCompany" />
            </el-tab-pane>
            <el-tab-pane v-if="isChange" label="零售电商" name="fourth">
                <div class="retailers_container">
                    <div :class="{ active: activeIndex == 1 }" class="item" @click="activeIndex = 1">店铺订单</div>
                    <div :class="{ active: activeIndex == 2 }" class="item" @click="activeIndex = 2">达人订单</div>
                </div>
                <OnlineRetailers
                    v-if="activeName == 'fourth' && activeIndex == 1"
                    ref="OnlineRetailersRef"
                    :source_type="activeIndex" />
                <MasterRetailers
                    v-if="activeName == 'fourth' && activeIndex == 2"
                    ref="MasterRetailersRef"
                    :source_type="activeIndex" />
            </el-tab-pane>
            <el-tab-pane v-if="isFirm == 2" label="合同" name="fifth">
                <Contract v-if="activeName == 'fifth'" ref="ContractRef"></Contract>
            </el-tab-pane>
        </el-tabs>
        <ZWDepart ref="DepartRef" @submit="getZWDepartData" />
    </div>
</template>

<script setup lang="ts">
import { onMounted, computed, watch, ref, reactive, toRefs, nextTick } from 'vue';

import { useRoute } from 'vue-router';
import { getSetionId, IsNotEmpty, useCheckReal } from '@/utils/utils';
import { getEventList, getCustomerDynamicList } from '@/api/customerCenter';

import CardTitle from './CardTitle.vue';
import List from './List.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import FollowTable from './FollowTable.vue';
import Business from './Business.vue';
import OnlineRetailers from './OnlineRetailers.vue';
import MasterRetailers from './MasterRetailers.vue';
import Contract from './Contract.vue';

// 是否地产用户
const isReal = useCheckReal();
const props = defineProps(['stepList', 'isCompany', 'isShowShop']);
const { stepList, isCompany } = toRefs(props);
const route = useRoute();
const isChange = ref(false);
const activeName = ref('first');
// 零售电商
const activeIndex = ref(1);
const isFirm: any = route.query.type;
interface State {
    cascaderOptions: any;
    formData: {
        cascaderValue: any;
        userValue: number[];
    };
    userOption: Array<{ id: number; name: string | number | undefined }>;
    dataList: any;
    time: string;
    sorter: { pageNum: number; pageSize: number; total: number };
}
const DepartRef = ref(null);
const FollowTableRef = ref(null);
const BusinessRef = ref(null);

const isLoading = ref(false);

const firstLoaded = ref(true);
const work_user_id = ref(0);
const state = reactive({
    formData: {
        cascaderValue: [],
        userValue: []
    },
    userOption: [],
    dataList: [],
    time: '',
    filterTime: [],
    sorter: {
        pageNum: 1,
        pageSize: 15,
        total: 0
    }
});
const cascaderProps = {
    expandTrigger: 'hover',
    label: 'name',
    value: 'id'
};
const eventList = () => {
    getEventList({ event_type: '1' }).then((res: any) => {
        state.cascaderOptions = res?.length === 1 ? res[0].children : res;
    });
};

// 获取页面初始化数据
const getData = (t?: string) => {
    const param = {
        cust_id: route.query.id,
        behaviour_id: !IsNotEmpty(state.formData.cascaderValue)
            ? ''
            : state.formData.cascaderValue[state.formData.cascaderValue.length - 1],
        behaviour_time: state.time,
        work_user_ids: state.formData.userValue,
        page: state.sorter.pageNum,
        page_size: state.sorter.pageSize,
        type: 1 //1 客户 2 客户群
    };
    isLoading.value = true;

    getCustomerDynamicList(param).then((res: any) => {
        isLoading.value = false;
        state.sorter.total = res?.total;
        if (t === 'creat') {
            state.dataList = res.data;
        } else {
            state.dataList = [...state.dataList, ...res.data];
        }
        if (firstLoaded.value && res.data.length > 0) {
            firstLoaded.value = false;
        }
    });
};

const handleClick = (e: any) => {
    activeName.value = e;
    getOther();
};
const onChangeCardTitle = (e: any) => {
    state.sorter.pageNum = 1;
    state.filterTime = e;
    state.time = e.join('~');
    getOther();
};
const getOther = () => {
    if (activeName.value == 'first') {
        getData('creat');
    }
    // 跟进
    if (activeName.value == 'second') {
        nextTick(() => {
            FollowTableRef.value.seachFun();
        });
    }
    // 商机
    if (activeName.value == 'third') {
    }
};

const onChangeList = (e: any) => {
    state.sorter.pageNum = state.sorter.pageNum + 1;
    getData();
};

/**
 * @des 客户动态-行为：点击查询和清空事件
 * @param isInit true -> 清空，false -> 查询
 */
const onSubmit = (isInit: boolean) => {
    state.sorter.pageNum = 1;
    // 如果是点击清空时，清空表单筛选项
    if (isInit) {
        state.formData.cascaderValue = [];
        state.formData.userValue = [];
    }
    getData('creat');
};
//打开 选择员工弹框
const openDepart = () => {
    DepartRef.value.selectedMember = state.formData.userValue.length > 0 ? state.userOption : [];
    DepartRef.value.multiple = true; //是否多选
    DepartRef.value.departVisble = true;
};
// 获取当前选中的员工的数据
const getZWDepartData = (val: any) => {
    state.userOption = val;
    state.formData.userValue = getSetionId('id', val);
};
const changeDepart = (data: any) => {
    state.userOption = state.userOption.filter((item: any) => data.includes(item.id));
    state.formData.userValue = getSetionId('id', state.userOption);
};
watch(
    () => props.isShowShop,
    val => {
        isChange.value = val;
    }
);
onMounted(() => {
    eventList();
});
</script>

<style lang="scss" scoped>
.customer-card {
    padding: 16px 20px;

    .demo_tabs {
        margin-top: 10px;

        // :deep(.el-tabs__content){
        //   min-height: 350px;
        // }
    }

    .el-form {
        display: flex;
        align-items: center;
        height: 64px;
        margin-top: 16px;
        padding: 0 16px;
        background: #f9f9f9;

        .el-form-item {
            margin: 0 40px 0 0;

            &:last-of-type {
                flex: auto;
                margin: 0;
                text-align: right;
            }
        }
    }
}

// 零售订单
.retailers_container {
    display: flex;
    flex-direction: row;
    margin: 24px 0;

    .item {
        width: 100px;
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #34302d;
        line-height: 20px;
        border: 1px solid #eaeaea;
        padding: 6px 0;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
    }

    .active {
        border: 1px solid #ff6b00;
        color: #ff6b00;
        border-right: 1px solid #ff6b00;
    }
}
</style>
